package net.eldeen.stockhack.service;

import java.io.IOException;
import java.util.List;
import java.util.Set;
import java.util.TimerTask;

import org.apache.log4j.Logger;
import org.xml.sax.SAXException;

import net.eldeen.stockhack.model.Stock;

public class AsyncDataFetcher<T extends DataFetcher<String>> extends TimerTask implements DataObservee<List<Stock>>{

  private static final Logger LOGGER = Logger.getLogger(AsyncDataFetcher.class);	
	
  private T dataFetcher;
  private String result;

  private StockDigester stockDigester;
  
  private Set<DataObserver<List<Stock>>> observers;

  public void setDataFetcher(T dataFetcher) {
    this.dataFetcher = dataFetcher;
  }

  public String getResult() {
    return result;
  }

  @Override
  public void run() {
    result = dataFetcher.fetch();
    
    try {
    	//convert results string to stock objects
		List<Stock> stocks = stockDigester.digest(result);
		notifyObservers(stocks);
	} catch (IOException e) {
		LOGGER.warn("Not updating observers", e);
	} catch (SAXException e) {
		LOGGER.warn("Not updating observers", e);
	}
    
  }

  public void addObserver(DataObserver<List<Stock>> observer) {
    observers.add(observer);
  }

  public void notifyObservers(List<Stock> data) {

    for (DataObserver<List<Stock>> observer : observers) {
      observer.update(data);
    }

  }

}
